<?php

namespace App\Http\Controllers\Home;

use App\Http\Controllers\Controller;
use App\Models\Admin\Agent;
use App\Models\Admin\PointsMall;
use App\Models\Admin\PointsMallOrder;
use App\Models\AgentRole;
use App\Models\CouponOrder;
use App\Models\User;
use App\Service\AgentService;
use App\Service\MasterService;
use App\Service\HttpService;
use GuzzleHttp\Exception\GuzzleException;
use Illuminate\Http\Request;
use App\Models\Master;
use App\Models\Coupon;
use Illuminate\Support\Facades\DB;
use App\Http\Controllers\Home\UsersController;
//use SoapClient;

use Phpro\SoapClient\Soap;

use Illuminate\Support\Facades\Hash;

//use SoapWrapper;

class AgentController extends Controller
{

    CONST PER_PAGE = 10;

    /**
     * 成为导购员
     * @param AgentService $agentService
     * @param HttpService $httpService
     * @return \Illuminate\Http\JsonResponse
     */
    public function agentApply(AgentService $agentService,HttpService $httpService)
    {
        $agent = request('agent') ?? '';
        $mobile = request('mobile') ?? '';
        if ($agent) {
            if (!checkMobile($agent)) {
                return tips(-1, 'error', '手机号码格式不正确');
            }

            // 判断是否是会员
            $url = config('app.url').'member_check?mobile='.$mobile;
            try {
                $res = $httpService->HttpRequest($url, 'GET');
            }catch (\Exception $e){
                return tips(-1,'error',$e->getMessage());
            } catch (GuzzleException $e) {
                return tips(-1,'error',$e->getMessage());
            }
            if($res['status'] == -1 || $res['status'] == 0){
                return tips(-1,'error','上级手机号码未注册会员');
            }

            $params['agent'] = $agent;
        }

        if (!checkMobile($mobile)) {

            return tips(-1, 'error', '手机号码格式不正确');
        }

        // 判断是否是会员
        $url = config('app.url').'member_check?mobile='.$mobile;
        try {
            $res = $httpService->HttpRequest($url, 'GET');
        }catch (\Exception $e){
            return tips(-1,'error',$e->getMessage());
        } catch (GuzzleException $e) {
            return tips(-1,'error',$e->getMessage());
        }
        if($res['status'] == -1){
            return tips(-1,'error','未注册会员');
        }

        $avatar = request('avatar') ?? '';
        $name = request('name') ?? '';

        DB::beginTransaction();
        try {
            $agentInfo = $agentService->getAgent(['mobile' => $mobile]);
            if (!$agentInfo) {
                $params['mobile'] = $mobile;
                $params['avatar'] = $avatar;
                $params['name'] = $name;
                $addAgent = $agentService->store($params);
                if (!$addAgent) {
                    throw new \Exception('数据库添加时出错');
                }
            }
        } catch (\Exception $e) {
            DB::rollBack();
            return tips(-1, 'error', $e->getMessage());
        }
        DB::commit();
        return tips(1, 'success', $params??[]);
    }

    public function AgentInfo(HttpService $httpService,Agent $agent){
        $mobile = request('mobile');

        if (!checkMobile($mobile)) {
            return tips(-1, 'error', '手机号码格式不正确');
        }

        // 判断是否是会员
        $url = config('app.url').'member_check?mobile='.$mobile;
        try {
            $res = $httpService->HttpRequest($url, 'GET');
        }catch (\Exception $e){
            return tips(-1,'error',$e->getMessage());
        } catch (GuzzleException $e) {
            return tips(-1,'error',$e->getMessage());
        }

        if($res['status'] == -1){
            return tips(-1,'error','未注册会员');
        }

        $agentInfo = $agent->getAgentInfo(['mobile'=>$mobile]);
        $agentInfo->total_count = $agent->getAgentTotalCount()??0;    //总推荐
        $agentInfo->today_count = $agent->getAgentTodayCount()??0;    //今天推荐
        return $agentInfo;
    }

    /**
     *
     * @param Agent $agent
     * @param CouponOrder $couponOrder
     * @param HttpService $httpService
     * @return \Illuminate\Http\JsonResponse
     * @author Bryant
     * @date 2020-09-08 10:07
     *
     *  我的推荐里列表
     */
    public function AgentList(Agent $agent,CouponOrder $couponOrder,HttpService $httpService,User $user){


      /*  libxml_disable_entity_loader(false);
        $opts = array(
            'ssl'   => array(
                'verify_peer'          => false
            ),
            'https' => array(
                'curl_verify_ssl_peer'  => false,
                'curl_verify_ssl_host'  => false
            )
        );
        $streamContext = stream_context_create($opts);

        $ws = "http://poqas01.zhouheiya.cn:50000/XISOAPAdapter/MessageServlet?senderParty=&senderService=BS_ZHY_APP_Q&receiverParty=&receiverService=&interface=SI_MEMBER_POINTS_DATA_Sender&interfaceNamespace=http://www.zhy.com/app/member_points";
        $client = new \SoapClient($ws);
        //$client ->debugLastSoapRequest();
        dd($client);*/

        $mobile = request('mobile');

        if (!checkMobile($mobile)) {

            return tips(-1, 'error', '手机号码格式不正确');
        }


        // 判断是否是会员
        $url = config('app.url').'member_check?mobile='.$mobile;
        try {
            $res = $httpService->HttpRequest($url, 'GET');
        }catch (\Exception $e){
            return tips(-1,'error',$e->getMessage());
        } catch (GuzzleException $e) {
            return tips(-1,'error',$e->getMessage());
        }
        if ($res['status'] == -1 || $res['status'] == 0) {

            return tips(-1,'error','未注册会员');
        }

        $total_count = $agent->getAgentTotalCount(['agent'=>$mobile]);   //总推荐

        $today_count = $agent->getAgentTodayCount(['agent'=>$mobile]);   //今天推荐
        //获取每个用户的累计收益
        $list = Agent::where('agent',$mobile)->groupBy('mobile')->paginate();

        if ($list) {
            foreach($list->items() as $v){
                $v -> count = DB::table('zhy_coupon_order')
                    ->where('agent',$mobile)
                    ->where('mobile',$v->mobile)
                    ->where('coupon_status',1)
                    ->sum('rate_money');
                $info = $user->where('mobile',$v->mobile)->first();

                if(!empty($info)){
                    $v -> avatar = $info['avatar'];
                    $v -> name = $info['name'];
                }else{
                    $v -> avatar = '';
                    $v -> name = '';
                }
            }
        }
        return tips(1,'success',[
            'total' => $total_count,           // 总条数
            'today' => $today_count,     // 今天的荐客数
            'list' => $list
        ]);

    }

    /**
     *
     * @author Bryant
     * @date 2020-09-03 10:08
     *
     * 成为导购员
     */
    function setAgent(HttpService $httpService,MasterService $masterService,AgentRole $agentRole)
    {

        // 拿到用户等级判断
        $mobile = request('mobile');

        $queryStr = request(['queryStr']); // 参数根据手机号

        $queryType = request(['queryType']);  // 类型根据手机号

        $activity = $agentRole->where('unique_code','ZHYSHARE')->first();


        $level = $activity['user_level']; // 后期可以根据后台定义的字段去判断

        if (!$queryStr || !$queryType) {

            return tips(-1, 'error', '参数错误');
        }
        // 判断用户是否注册周黑鸭会员
        $isUser = $this->isUser($httpService,$mobile);

        // 地区
        $area = request('area');
        //详细地址
        $street = request('street');

        if ($isUser['status'] == -1 || $isUser['status'] == 0) {

            return tips(-1, 'error', '该用户没有注册周黑鸭会员');
        }
        // 查询会员等级
        $user = $this->getUser($httpService,$queryStr,$queryType);

        if($user['statu'] !=1){

            return tips(-1, 'error', '用户信息错误');
        }

        if ($user['level']) {

            $user['level'] = substr($user['level'],-1);

            if ($user['level'] < $level) {

                return tips(-1, 'error', '会员等级不够暂时不能成为导购员');
            }
        }

        $agentInfo = $masterService->getMaster(['mobile' => $mobile]);

        if($agentInfo){

            if($agentInfo['status'] == 0 || $agentInfo['status'] == 1){

                return tips(-1,'error','您已提交申请,请勿重复操作');
            }
        }


        try {
            // 没有就添加
            if (!$agentInfo) {
                $params['mobile'] = $mobile;
                $params['status'] = 0; //状态初始化
                $params['user_id'] = 0;
                $params['area'] = $area;
                $params['street'] = $street;
                $params['created_at'] = date('Y-m-d H:i:s',time());
                $addAgent = $masterService->store($params);
                if (!$addAgent) {
                    throw new \Exception('数据库添加时出错');
                }
            }
            /*// 驳回就更新
            if($agentInfo['status'] == 2){

                $where = ['mobile'=>$mobile];

                $data['status'] = 0; //初始化状态
            }*/
        } catch (\Exception $e) {
            DB::rollBack();
            return tips(-1, 'error', $e->getMessage());
        }
        DB::commit();

        return tips(1, 'success','提交申请成功请等待审核');


    }

    /**
     *
     * @param Request $request
     * @param Master $master
     * @return \Illuminate\Http\JsonResponse
     * @author Bryant
     * @date 2020-09-18 17:05
     *
     *  设置导购员地区
     */
    public function setArea(Request $request,Master $master)
    {
        // 参数
        $mobile = request('mobile');
        if (!$mobile) {
            return tips(-1,'error','参数错误');
        }
        // 地区
        $data['area'] = request('area');
        $res = $master->where('mobile',$mobile)->update($data);

        if ($res) {
            return tips(1,'error','更新成功');
        } else {
            return tips(-1,'error','更新失败');
        }

    }

    /**
     *
     * @author Bryant
     * @date 2020-09-03 16:20
     *
     *  领取二维码绑定关系
     */
    public function userAgent(HttpService $httpService,AgentService $agentService,CouponOrder $couponOrder,AgentRole $agentRole,Coupon $coupon)
    {
        // 绑定关系
        $agent = request('agent'); //上级的手机号

        if (!$agent) {

            return tips(-1, 'error', '参数错误');
        }
        // 当前用户的手机号
        $mobile = request('mobile');

        if (!$mobile) {
            return tips(-1, 'error', '参数错误');
        }

        if ($mobile == $agent) {

            return tips(-1,'error','请勿自我领取');
        }
        // 获取活动规则
        $activity = AgentRole::where('unique_code','ZHYSHARE')->first();
        if (!$activity) {

            return tips(-1, 'error','该活动不存在');
        }
        // 判断有效期
        $time = strtotime($activity['end_time']);
        if (time() >$time) {

            return  tips(-1,'error','该活动已过有效期');
        }
        // 获取优惠券的批次号
        $coupon_code = $activity['coupon_code']; //暂时写死等接口接通再获取真实数据

        // 获得该批次号优惠券的数量
        $coupon = Coupon::where('coupon_code',$coupon_code)->first();

        if ($coupon['coupon_num'] <= 0) {

            return tips(-1,'error','该优惠券已经领取完了');
        }

        // 获取当前用户的领取次数

        $orderNUm = CouponOrder::where('coupon_code',$coupon_code)->where('mobile',$mobile)->count('id');

        if ($orderNUm > $coupon['pre_num']) {

            return tips(-1,'error','您已经领取过该优惠券了');
        }

        // 会员根据批次号获取

        // 判断上级用户是否注册周黑鸭会员
        $isUser = $this->isUser($httpService,$agent);
        if ($isUser['status'] == -1 || $isUser['status'] == 0) {
            return tips(-2, 'error', '上级用户尚未注册');
        }
        // 判断当前用户是否注册周黑鸭会员
        $userInfo = $this->isUser($httpService,$mobile);
        if ($userInfo['status'] == -1 || $userInfo['status'] == 0) {
            return tips(-2, 'error', '您尚未注册');
        }
        // 获取CRM 的数据
        $getUrl = "http://8.129.17.60:8898"; //C# 中间件的访问地址
        $param = [
            'action' => 'DT_COUPONISSUANCE_REQ',
            'ZCOUPXH' => $coupon_code,
            //'ZPARTNER_ID'=> "",
            'ZCPNUMTO' =>"1",
            'ZCPBDDAT' =>date('Y-m-d',time()),
            'ZREFIELD2' => 'HNX',
            'ZREFIELD3' => $mobile

        ];
        $param = json_encode($param,true);
        //dd($param);
        $res = $this->curl_open($getUrl,$param);
        //dd($res);
        if($res['rtval']['T_RETURN'][0]['TYPE'] == 'S'){
            $coupon_num = $res['rtval']['T_OUT_ISSUANCE'][0]['ZZCPIDO'] ?? 0;
        }else{
            return tips(-1,'error',$res['rtval']['T_RETURN'][0]['MESSAGE']);
        }

        // 该批次号优惠券核销对应的奖励
        $rate_money = $activity['rate_money'];

        $agentInfo = $agentService->getAgent(['agent'=>$agent,'mobile'=>$mobile]);
        DB::beginTransaction();
        try {
            if (!$agentInfo) {
                //组装数据加入相关的关系表 第一次加入关系表
                $data = [
                    'agent'  => $agent,
                    'mobile' => $mobile,
                    'status' => 1,
                    'created_at' => date('Y-m-d H:i:s',time()),
                 ];

                $res = $agentService->store($data);
                if (!$res) {
                    throw new \Exception('数据库添加时出错');
                }
            }

            // 加入下级用户消费列表
            $datas = [
                'coupon_code' => $coupon_code,// 优惠券的券号
                'coupon_num' => $coupon_num,
                'mobile' => $mobile,// 领取用户的手机号
                'agent' => $agent,// 上级代理的
                //'user_id' => $memberId ?? 0,
                'coupon_status' => 0, // 初始化
                'total_money' => 0, //优惠券的金额
                'rate_money' => $rate_money, // 收益的金额
                'created_at' => date('Y-m-d H:i:s',time()),
            ];

            $result = $couponOrder->insert($datas);

            // 将该批次号的优惠券数量减一
            DB::table('coupon')->where('coupon_code',$coupon_code)->decrement('coupon_num');
            if (!$result) {
                throw new \Exception('数据库添加时出错');
            }

        } catch (\Exception $e) {
            DB::rollBack();
            return tips(-1, 'error', $e->getMessage());
        }
        DB::commit();


        return tips(1, 'success','领取成功');

    }

    /**
     *
     * @param HttpService $httpService
     * @param User $userModel
     * @return \Illuminate\Http\JsonResponse
     * @throws GuzzleException
     * @author Bryant
     * @date 2020-09-07 20:20
     *
     * 获取分享二维码
     */
    public function getQrcode(HttpService $httpService,User $userModel,MasterService $masterService)
    {
        $user_id = request('mobile');

        if (empty($user_id)) {

            return tips(-1,'error','请选择分享的用户');
        };
        $user = $masterService->getMaster(['mobile'=>$user_id]);


        if ($user['status'] != 1) {

            return tips(-1,'error','您暂时无法分享');
        }
        $qr_path = "./uploads/";
        if(!file_exists($qr_path.'sp/')){
            mkdir($qr_path.'sp/', 0700,true);//判断保存目录是否存在，不存在自动生成文件目录
        }
        $filename = 'sp/'.time().'.png';
        $file = $qr_path.$filename;

        $access = $this->getAccent($httpService);

        $access_token= $access['access_token'];
        $url = 'https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token='.$access_token;

        $qrcode = array(
            'scene'			=> 'id='.$user_id,//二维码所带参数
            'width'			=> 300,
            'page'			=> 'pages/distributionCenter/receive/receive',//二维码跳转路径（要已发布小程序）
            'auto_color'	=> true
        );

        $result = $httpService->HttpRequest($url,'POST',$qrcode);//请求微信接口


        // 错误码
        $errcode = json_decode($result,true)['errcode'];
        // 错误信息
        $errmsg = json_decode($result,true)['errmsg'];

        if($errcode) {

            return tips(-1,'error',$errmsg);
        }

        $res = file_put_contents($file,$result);//将微信返回的图片数据流写入文件


        //判断是否已存在该二维码图片
        $img =$userModel->where('mobile',$user_id)->value('share_qrcode');


        if($res===false){
            return tips(-1,'error','生成二维码失败');
        }else{
            //返回图片地址链接给前端，入库操作
            $fName = '/uploads/'.$filename;

            if (isset($img) && !empty($img)){
                //返回图片链接信息
                return tips(1,'success',$img);

            }else{
                //否则，添加一条新的记录
                $dataArr['share_qrcode'] = $fName ;
                $userModel->where('mobile',$user_id)->update($dataArr);
                return tips(1,'success',$fName);
            }
        }
    }


    /**
     *
     * @author Bryant
     * @date 2020-09-09 10:22
     *
     *  分销中心
     */
    public function getIndex(Request $request,User $user,Agent $agent,CouponOrder $couponOrder)
    {
        // 手机号
        $mobile = request('mobile');
        // 查询出所有的下级订单 未完成的订单
        $list = CouponOrder::where('agent',$mobile)->where('coupon_status',0)->get();
        if($list){
            // 因为CRM 接口每次只提供一次查询。暂时只提供单词查询
            foreach ($list as $key=>$value) {

                // 拿到手机号去查询用户优惠券的信息 第三方CRM 接口
                // 获取CRM 的数据
                $getUrl = "http://8.129.17.60:8898"; //C# 中间件的访问地址

                //{"action":"DT_PAR_CON_SEL_Req", "ZPARTNER_ID":"1001128505"}
                $param = [
                    'action' => 'DT_PAR_CON_SEL_Req',
                    'ZPARTNER_ID'=> "",
                    'MOB_NUMBER' => "$value->mobile"."/HNX",
                    'ZCPIDO' => $value->coupon_num,
                ];
                $param = json_encode($param,true);
                $res = $this->curl_open($getUrl,$param);
                // 已使用的状态
                if($res['rtval']['E_DATA'][0]['ZCPSTATE'] == 'J03'){
                    $result = CouponOrder::whrer('mobile',$value->mobile)
                        ->where('coupon_num',$value->coupon_num)
                        ->update(['coupon_status'=>1]);
                }

            }

        }

        if (!$mobile) {
            return tips(-1,'error','参数错误');
        }
        // 用户的信息
        $userInfo  = $user->where('mobile',$mobile)->first();

        if ($userInfo) {
            if (empty($userInfo['rate_money'])) {

                $userInfo['rate_money'] = 0;
            }
        }
        // 获取用户的总推荐和今日推荐人数
        $total_count = $agent->getAgentTotalCount(['agent'=>$mobile]);   //总推荐
        $today_count = $agent->getAgentTodayCount(['agent'=>$mobile]);   //今天推荐
        // 今天的收益
        $today_money = $couponOrder -> where('agent',$mobile)
            ->whereBetween('use_time',[date('Y-m-d 00:00:00', time()),date('Y-m-d 23:59:59', time())])
            ->where('coupon_status',1)
            ->sum('rate_money');

        $data = [

            'userInfo' => $userInfo, // 会员信息
            'total_count' => $total_count, // 总推荐人数
            'today_count' => $today_count, // 今日推荐人数
            'today_money' => $today_money

        ];
        return tips(1,'success',$data);

    }

    /**
     *
     * @param Master $master
     * @return \Illuminate\Http\JsonResponse
     * @author Bryant
     * @date 2020-09-11 15:20
     *
     * 判断用户是否是会员
     */
    public function getStatus(Request $request,Master $master)
    {
        // 当前会员手机号
        $mobile = request('mobile');

        if(!$mobile){

            return tips(-1,'error','参数错误');
        }
        //查询是否已经导购员

        $status = $master->where('mobile',$mobile)->value('status');

        if(!$status){

            return tips(-1,'error','你暂时没有申请成为导购员');
        }

        return tips(1,'success',$status);

    }

    /**
     *
     * @author Bryant
     * @date 2020-09-11 17:43
     *
     *
     */
    public function getUserMoney(Request $request,User $user,Agent $agent,CouponOrder $couponOrder)
    {
        // 手机号
        $mobile = request('mobile');

        if (!$mobile) {

            return tips(-1,'error','参数错误');
        }

        $userInfo = $user->where('mobile',$mobile)->first();

        if($userInfo){

            if (empty($userInfo['rate_money'])) {

                $userInfo['rate_money'] = 0;
             }
        }

        // 获取用户的总推荐和今日推荐人数
        $total_count = $agent->getAgentTotalCount(['agent'=>$mobile]);   //总推荐
        $today_count = $agent->getAgentTodayCount(['agent'=>$mobile]);   //今天推荐
        // 今天的收益
        $today_money = $couponOrder -> where('agent',$mobile)
            ->whereBetween('use_time',[date('Y-m-d 00:00:00', time()),date('Y-m-d 23:59:59', time())])
            ->where('coupon_status',1)
            ->sum('rate_money');
        // 获取下级用户
        $orderlist = $couponOrder->where('agent',$mobile)->where('coupon_status',1)->paginate();
        // 统计手机号
        $mobiles = [];
        if ($orderlist) {
            foreach($orderlist->items() as $key=>$v){
                $mobiles[] = $v->mobile;
            }
            // 下级用户的信息
            $userList = $user->whereIn('mobile',$mobiles)->get();

            if($userInfo){
                foreach($orderlist->items() as $value){
                    if($value->use_time){
                        $time = strtotime($value->use_time);

                        $value->use_time = date('Y-m-d',$time);
                    }
                    foreach($userList as $v){
                        if($value->mobile == $v['mobile']){
                            $value->username = $v['name'];
                            $value->head_img = $v['avatar'];
                        }
                    }
                }
            }
        }


        $data = [

            'userInfo' => $userInfo,
            'total_count' => $total_count,
            'today_count' => $today_count,
            'today_money' => $today_money,
            'orderList' => $orderlist,
        ];

        return tips(1,'success',$data);
    }


}
